/**
 * 优化后的筛选排序逻辑（优先级：当前连续错误 → 低准确率 → 高频错误）
 * 准确率: 0.77
 */
const _ = require('lodash')

// 配置文件（基于验证数据调整）
const CONFIG = {
  THRESHOLDS: {
    EMERGENCY_INCORRECT: 3, // 从2调整为3，避免过度敏感
    WEAK_ACCURACY: 0.68, // 从0.75降至0.68，扩大处理范围
    HIGH_ERROR_DENSITY: 0.25, // 从0.3降到0.25，更严格密度控制
    MAX_CON_INCORRECT_ALERT: 4 // 从3升到4，减少误报
  },
  WEIGHTS: {
    CURRENT_INCORRECT: 0.4, // 权重从0.6降至0.4
    ACCURACY: 0.5, // 权重从0.3升至0.5
    ERROR_DENSITY: 0.1
  }
}

// 增强版优先级算法（添加非线性因子）
function calculatePriorityScore(stats) {
  const errorDensity = calculateErrorDensity(stats)

  // 准确率平方增益（低准确率放大效果）
  const accuracyGain = Math.pow(1 - stats.accuracyRate, 2) * 15

  // 当前错误次数上限控制（防止单指标主导）
  const clampedIncorrect = Math.min(stats.currentConsecutiveIncorrect, 5)

  return _.round(
    CONFIG.WEIGHTS.CURRENT_INCORRECT * clampedIncorrect +
      CONFIG.WEIGHTS.ACCURACY * accuracyGain +
      CONFIG.WEIGHTS.ERROR_DENSITY * errorDensity * 100 * Math.log(stats.consecutiveIncorrectSegments + 1),
    2
  )
}

// 改进的错误密度计算（考虑绝对数量）
function calculateErrorDensity(stats) {
  const total = stats.consecutiveCorrectSegments + stats.consecutiveIncorrectSegments
  if (total === 0) return 0

  // 添加绝对数量衰减因子
  const absoluteFactor = 1 - Math.exp(-stats.consecutiveIncorrectSegments / 10)
  return (stats.consecutiveIncorrectSegments / total) * absoluteFactor
}

// 修正稳定性计算（防止除零错误）
function calculateStabilityIndex(stats) {
  const safeDivision = (a, b) => (b === 0 ? 0 : a / b)
  const correctStability = safeDivision(stats.avgConsecutiveCorrect, stats.maxConsecutiveCorrect)
  const incorrectStability = 1 - safeDivision(stats.avgConsecutiveIncorrect, stats.maxConsecutiveIncorrect || 1)
  return _.round(correctStability * incorrectStability, 2)
}

// 优化分组数量计算（添加下限保护）
function calculateOptimalGroupCount(groups) {
  const accuracyRates = groups.map((g) => g.stats.accuracyRate)
  const avgAccuracy = _.mean(accuracyRates)

  let ratio
  if (avgAccuracy < 0.65) ratio = 0.45
  else if (avgAccuracy < 0.75) ratio = 0.35
  else ratio = 0.25

  return Math.max(20, Math.floor(groups.length * ratio)) // 至少保留20组
}

// 核心算法流程优化
module.exports = (currentGroupArray) => {
  return (
    _.chain(currentGroupArray)
      // 第一阶段：增强型过滤
      .filter((item) => {
        const s = item.stats
        const totalSegments = s.consecutiveCorrectSegments + s.consecutiveIncorrectSegments
        const errorDensity = calculateErrorDensity(s)

        return (
          s.currentConsecutiveIncorrect >= CONFIG.THRESHOLDS.EMERGENCY_INCORRECT ||
          s.accuracyRate < CONFIG.THRESHOLDS.WEAK_ACCURACY ||
          (totalSegments > 10 && errorDensity > CONFIG.THRESHOLDS.HIGH_ERROR_DENSITY) || // 添加最小数据量要求
          s.maxConsecutiveIncorrect >= CONFIG.THRESHOLDS.MAX_CON_INCORRECT_ALERT
        )
      })
      // 第二阶段：平衡排序
      .orderBy(
        [
          (item) => calculatePriorityScore(item.stats),
          (item) => -item.stats.accuracyRate,
          (item) => -item.stats.avgConsecutiveCorrect // 新增稳定性排序
        ],
        ['desc', 'asc', 'desc']
      )
      // 第三阶段：智能截取
      .take(calculateOptimalGroupCount(currentGroupArray))
      // 第四阶段：增强元数据
      .map((item) => ({
        ...item,
        _meta: {
          priorityScore: calculatePriorityScore(item.stats),
          errorDensity: calculateErrorDensity(item.stats),
          stability: calculateStabilityIndex(item.stats),
          accuracyStatus: item.stats.accuracyRate < 0.7 ? 'critical' : 'normal'
        }
      }))
      .value()
  )
}
